package com.ckx.vaild;

import com.ckx.annotation.ContainNum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义校验器
 *  针对固定数值范围进行校验 比如： 要求只能是 1、2其它数字不行
 */
public class ContainNumValidator implements ConstraintValidator<ContainNum, Integer> {

    private Set<Integer> set = new HashSet<>();

    @Override
    public void initialize(ContainNum constraintAnnotation) {
        int[] value = constraintAnnotation.value();
        if (value.length>0){
            for (int i : value) {
                set.add(i);//收集数据
            }
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.size()>0 && set.contains(value);
    }
}
